package com.kakarote.hrm.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.core.common.MultipartFileUtil;
import com.kakarote.core.common.Result;
import com.kakarote.core.common.cache.AdminCacheKey;
import com.kakarote.core.common.enums.FieldEnum;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.UploadEntity;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.service.AdminFileService;
import com.kakarote.core.redis.Redis;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.ExcelParseUtil;
import com.kakarote.hrm.constant.PositionProcessIsEnum;
import com.kakarote.hrm.entity.BO.QueryRecruitProcesPageListBO;
import com.kakarote.hrm.entity.PO.HrmRecruitPlan;
import com.kakarote.hrm.entity.PO.HrmRecruitPlanRecord;
import com.kakarote.hrm.entity.PO.HrmRecruitPosition;
import com.kakarote.hrm.entity.PO.HrmRecruitProces;
import com.kakarote.hrm.entity.VO.RecruitPlanRecordVO;
import com.kakarote.hrm.entity.VO.RecruitProcesExportVO;
import com.kakarote.hrm.entity.VO.RecruitProcesVO;
import com.kakarote.hrm.mapper.HrmRecruitProcesMapper;
import com.kakarote.hrm.service.IHrmRecruitPlanRecordService;
import com.kakarote.hrm.service.IHrmRecruitPlanService;
import com.kakarote.hrm.service.IHrmRecruitPositionService;
import com.kakarote.hrm.service.IHrmRecruitProcesService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 招聘过程 服务实现类
 * </p>
 *
 * @author system
 * @since 2024-01-01
 */
@Service
public class HrmRecruitProcesServiceImpl extends BaseServiceImpl<HrmRecruitProcesMapper, HrmRecruitProces> implements IHrmRecruitProcesService {

    @Autowired
    private HrmRecruitProcesMapper recruitProcesMapper;
    @Autowired
    private HrmRecruitPlanRecordServiceImpl hrmRecruitPlanRecordService;
    @Autowired
    private IHrmRecruitPlanService hrmRecruitPlanService;
    @Autowired
    private IHrmRecruitPositionService hrmRecruitPositionService;
    @Autowired
    private Redis redis;
    @Resource
    private AdminFileService adminFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog addRecruitProces(HrmRecruitProces recruitProces) {
        RecruitPlanRecordVO recruitPlanRecordVO = hrmRecruitPlanRecordService.queryById(recruitProces.getRecordId());
        if (recruitPlanRecordVO == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "计划记录不存在");
        }
        recruitProces.setPlanId(recruitPlanRecordVO.getPlanId());
        save(recruitProces);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitProces.getProcesId(), "招聘过程");
        String detail = String.format("计划编号：%s，记录编号：%s，岗位编号：%s，报名数量：%d，入闱笔试数量：%d",
                recruitProces.getPlanId() != null ? recruitProces.getPlanId().toString() : "无",
                recruitProces.getRecordId() != null ? recruitProces.getRecordId().toString() : "无",
                recruitProces.getPositionId() != null ? recruitProces.getPositionId().toString() : "无",
                recruitProces.getRegistrationNum() != null ? recruitProces.getRegistrationNum() : 0,
                recruitProces.getWrittenNum() != null ? recruitProces.getWrittenNum() : 0);
        operationLog.setOperationInfo(detail);
        operationLog.setBehavior(BehaviorEnum.SAVE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog setRecruitProces(HrmRecruitProces recruitProces) {
        HrmRecruitProces oldProces = getById(recruitProces.getProcesId());
        if (oldProces == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "招聘过程不存在");
        }
        if (recruitProces.getRecordId() != null) {
            RecruitPlanRecordVO recruitPlanRecordVO = hrmRecruitPlanRecordService.queryById(recruitProces.getRecordId());
            if (recruitPlanRecordVO == null) {
                throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "计划记录不存在");
            }
            recruitProces.setPlanId(recruitPlanRecordVO.getPlanId());
        } else {
            recruitProces.setPlanId(null);
        }

        // 记录变更内容
        StringBuilder detail = new StringBuilder();
        if (!Objects.equals(oldProces.getPlanId(), recruitProces.getPlanId())) {
            detail.append(String.format("计划编号：%s → %s；",
                    oldProces.getPlanId() != null ? oldProces.getPlanId().toString() : "无",
                    recruitProces.getPlanId() != null ? recruitProces.getPlanId().toString() : "无"));
        }
        if (!Objects.equals(oldProces.getRecordId(), recruitProces.getRecordId())) {
            detail.append(String.format("记录编号：%s → %s；",
                    oldProces.getRecordId() != null ? oldProces.getRecordId().toString() : "无",
                    recruitProces.getRecordId() != null ? recruitProces.getRecordId().toString() : "无"));
        }
        if (!Objects.equals(oldProces.getPositionId(), recruitProces.getPositionId())) {
            detail.append(String.format("岗位编号：%s → %s；",
                    oldProces.getPositionId() != null ? oldProces.getPositionId().toString() : "无",
                    recruitProces.getPositionId() != null ? recruitProces.getPositionId().toString() : "无"));
        }
        if (!Objects.equals(oldProces.getRegistrationNum(), recruitProces.getRegistrationNum())) {
            detail.append(String.format("报名数量：%d → %d；",
                    oldProces.getRegistrationNum() != null ? oldProces.getRegistrationNum() : 0,
                    recruitProces.getRegistrationNum() != null ? recruitProces.getRegistrationNum() : 0));
        }
        if (!Objects.equals(oldProces.getWrittenNum(), recruitProces.getWrittenNum())) {
            detail.append(String.format("入闱笔试数量：%d → %d；",
                    oldProces.getWrittenNum() != null ? oldProces.getWrittenNum() : 0,
                    recruitProces.getWrittenNum() != null ? recruitProces.getWrittenNum() : 0));
        }
        if (!Objects.equals(oldProces.getIsWrittenExam(), recruitProces.getIsWrittenExam())) {
            detail.append(String.format("笔试是否达开考比例：%s → %s；",
                    oldProces.getIsWrittenExam() != null ? (oldProces.getIsWrittenExam() == 1 ? "是" : "否") : "无",
                    recruitProces.getIsWrittenExam() != null ? (recruitProces.getIsWrittenExam() == 1 ? "是" : "否") : "无"));
        }
        if (!Objects.equals(oldProces.getInterviewNum(), recruitProces.getInterviewNum())) {
            detail.append(String.format("入闱面试数量：%d → %d；",
                    oldProces.getInterviewNum() != null ? oldProces.getInterviewNum() : 0,
                    recruitProces.getInterviewNum() != null ? recruitProces.getInterviewNum() : 0));
        }
        if (!Objects.equals(oldProces.getIsInterviewExam(), recruitProces.getIsInterviewExam())) {
            detail.append(String.format("面试是否达开考比例：%s → %s；",
                    oldProces.getIsInterviewExam() != null ? (oldProces.getIsInterviewExam() == 1 ? "是" : "否") : "无",
                    recruitProces.getIsInterviewExam() != null ? (recruitProces.getIsInterviewExam() == 1 ? "是" : "否") : "无"));
        }
        if (!Objects.equals(oldProces.getCheckNum(), recruitProces.getCheckNum())) {
            detail.append(String.format("入闱体检人数：%d → %d；",
                    oldProces.getCheckNum() != null ? oldProces.getCheckNum() : 0,
                    recruitProces.getCheckNum() != null ? recruitProces.getCheckNum() : 0));
        }
        if (!Objects.equals(oldProces.getEstimateNum(), recruitProces.getEstimateNum())) {
            detail.append(String.format("拟聘用人数：%d → %d；",
                    oldProces.getEstimateNum() != null ? oldProces.getEstimateNum() : 0,
                    recruitProces.getEstimateNum() != null ? recruitProces.getEstimateNum() : 0));
        }

        updateById(recruitProces);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitProces.getProcesId(), "招聘过程");
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.UPDATE);
        return operationLog;
    }

    @Override
    public RecruitProcesVO queryById(Long procesId) {
        return recruitProcesMapper.queryById(procesId);
    }

    @Override
    public BasePage<RecruitProcesVO> queryRecruitProcesPageList(QueryRecruitProcesPageListBO queryRecruitProcesPageListBO) {
        BasePage<RecruitProcesVO> page = queryRecruitProcesPageListBO.parse();
        return recruitProcesMapper.queryRecruitProcesPageList(page, queryRecruitProcesPageListBO);
    }

    @Override
    public List<RecruitProcesVO> queryByPlanId(Long planId) {
        return recruitProcesMapper.queryByPlanId(planId);
    }

    @Override
    public List<RecruitProcesVO> queryByRecordId(Long recordId) {
        return recruitProcesMapper.queryByRecordId(recordId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteRecruitProces(Long procesId) {
        HrmRecruitProces proces = getById(procesId);
        if (proces == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "招聘过程不存在");
        }

        removeById(procesId);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(procesId, "招聘过程");
        operationLog.setOperationInfo(String.format("删除招聘过程，计划编号：%s，岗位编号：%s",
                proces.getPlanId() != null ? proces.getPlanId().toString() : "无",
                proces.getPositionId() != null ? proces.getPositionId().toString() : "无"));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog batchDeleteRecruitProces(List<Long> procesIds) {
        if (procesIds == null || procesIds.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "请选择要删除的招聘过程");
        }

        List<HrmRecruitProces> procesList = listByIds(procesIds);
        if (procesList.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "选择的招聘过程不存在");
        }

        removeByIds(procesIds);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(procesIds.toString(), "批量删除招聘过程");
        StringBuilder detail = new StringBuilder("删除招聘过程：");
        for (HrmRecruitProces proces : procesList) {
            detail.append("过程ID:").append(proces.getProcesId()).append("、");
        }
        if (detail.length() > 0) {
            detail.setLength(detail.length() - 1);
        }
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteByPlanId(Long planId) {
        Map<String, Object> params = new HashMap<>();
        params.put("plan_id", planId);
        List<HrmRecruitProces> procesList = listByMap(params);
        if (!procesList.isEmpty()) {
            recruitProcesMapper.deleteByPlanId(planId);
        }

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(planId, "删除计划下所有招聘过程");
        operationLog.setOperationInfo(String.format("删除计划下所有招聘过程，共%d个", procesList.size()));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteByRecordId(Long recordId) {
        Map<String, Object> params = new HashMap<>();
        params.put("record_id", recordId);
        List<HrmRecruitProces> procesList = listByMap(params);
        if (!procesList.isEmpty()) {
            recruitProcesMapper.deleteByRecordId(recordId);
        }

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recordId, "删除记录下所有招聘过程");
        operationLog.setOperationInfo(String.format("删除记录下所有招聘过程，共%d个", procesList.size()));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    public void exportRecruitProces(HttpServletResponse response, QueryRecruitProcesPageListBO queryRecruitProcesPageListBO) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "招聘过程_" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

        // 直接查询所有符合条件的数据（不分页）
        List<RecruitProcesVO> dataList = recruitProcesMapper.queryAllRecruitProcesList(queryRecruitProcesPageListBO);

        // 转换为导出VO
        List<RecruitProcesExportVO> exportList = new ArrayList<>();
        for (RecruitProcesVO vo : dataList) {
            RecruitProcesExportVO exportVO = new RecruitProcesExportVO();
            exportVO.setPlanName(vo.getPlanName());
            exportVO.setRecordCode(vo.getRecordCode());
            exportVO.setPositionName(vo.getPositionName());
            exportVO.setPositionCode(vo.getPositionCode());
            exportVO.setPositionUnit(vo.getPositionUnit());
            exportVO.setRegistrationNum(vo.getRegistrationNum());
            exportVO.setWrittenNum(vo.getWrittenNum());
            exportVO.setIsWrittenExamText(PositionProcessIsEnum.getNameByValue(vo.getIsWrittenExam()));
            exportVO.setInterviewNum(vo.getInterviewNum());
            exportVO.setIsInterviewExamText(PositionProcessIsEnum.getNameByValue(vo.getIsInterviewExam()));
            exportVO.setCheckNum(vo.getCheckNum());
            exportVO.setEstimateNum(vo.getEstimateNum());
            exportVO.setCreateTime(vo.getCreateTime());
            exportVO.setCreateRealName(vo.getCreateRealName());
            exportList.add(exportVO);
        }

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), RecruitProcesExportVO.class)
                .sheet("招聘过程")
                .doWrite(exportList);
    }

    @Override
    public void downloadExcel(HttpServletResponse response) {
        List<JSONObject> list = queryField();
        ExcelParseUtil.importExcel(new ExcelParseUtil.ExcelParseService() {
            @Override
            public String getExcelName() {
                return "招聘过程";
            }

            @Override
            public String getMergeContent(String module) {
                return "注意事项：\n" +
                        "1、表头标“*”的红色字体为必填项\n" +
                        "2、导入只新增不修改\n" +
                        "3、计划名称和计划编号必须已存在\n" +
                        "4、记录编号必须已存在\n" +
                        "5、岗位名称和岗位编号必须已存在并匹配\n" +
                        "6、报名数量必须大于等于0\n" +
                        "7、笔试是否达开考比例和面试是否达开考比例只能填写[是、否]，或者不填";
            }
        }, list, response, "user");
    }

    private List<JSONObject> queryField() {
        List<JSONObject> list = new ArrayList<>();
        list.add(queryField("planName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划名称", 1));
        list.add(queryField("planCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划编号", 1));
        list.add(queryField("recordCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "记录编号", 1));
        list.add(queryField("positionName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "岗位名称", 1));
        list.add(queryField("positionCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "岗位编号", 1));
        list.add(queryField("registrationNum", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "报名数量", 1));
        list.add(queryField("writtenNum", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "入闱笔试数量", 0));
        list.add(queryField("isWrittenExam", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "笔试是否达开考比例", 0));
        list.add(queryField("interviewNum", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "入闱面试数量", 0));
        list.add(queryField("isInterviewExam", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "面试是否达开考比例", 0));
        list.add(queryField("checkNum", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "入闱体检人数", 0));
        list.add(queryField("estimateNum", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "拟聘用人数", 0));
        return list;
    }

    private JSONObject queryField(String fieldName, String formType, Integer type, String name, Integer isNull) {
        JSONObject json = new JSONObject();
        json.fluentPut("fieldName", fieldName)
                .fluentPut("formType", formType)
                .fluentPut("type", type)
                .fluentPut("name", name).fluentPut("isNull", isNull);
        return json;
    }

    private String getFilePath(MultipartFile file) {
        String dirPath = FileUtil.getTmpDirPath();
        try {
            InputStream inputStream = file.getInputStream();
            File fromStream = FileUtil.writeFromStream(inputStream, dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename());
            return fromStream.getAbsolutePath();
        } catch (IOException e) {
            throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject excelImport(MultipartFile file) {
        List<List<Object>> errList = new ArrayList<>();
        String filePath = getFilePath(file);
        AtomicReference<Integer> num = new AtomicReference<>(0);
        //新增招聘过程
        List<HrmRecruitProces> addProcesList = new ArrayList<>();
        //查询所有招聘计划
        List<HrmRecruitPlan> planList = hrmRecruitPlanService.list();
        Map<String, HrmRecruitPlan> planMap;
        if (planList != null && !planList.isEmpty()) {
            planMap = planList.stream().collect(Collectors.toMap(item -> Optional.ofNullable(item.getPlanName()).orElse("") + Optional.ofNullable(item.getPlanCode()).orElse(""), Function.identity(), (v1, v2) -> v1));
        } else {
            planMap = new HashMap<>();
        }
        //查询所有招聘记录
        List<HrmRecruitPlanRecord> recordList = hrmRecruitPlanRecordService.list();
        Map<String, HrmRecruitPlanRecord> recordMap;
        if (recordList != null && !recordList.isEmpty()) {
            recordMap = recordList.stream().collect(Collectors.toMap(HrmRecruitPlanRecord::getRecordCode, Function.identity(), (v1, v2) -> v1));
        } else {
            recordMap = new HashMap<>();
        }
        //查询所有招聘岗位
        List<HrmRecruitPosition> positionList = hrmRecruitPositionService.list();
        Map<String, HrmRecruitPosition> positionMap;
        if (positionList != null && !positionList.isEmpty()) {
            positionMap = positionList.stream().collect(Collectors.toMap(item -> {
                Long planId = Optional.ofNullable(item.getPlanId()).orElse(0L);
                String name = Optional.ofNullable(item.getPositionName()).orElse("");
                String code = Optional.ofNullable(item.getPositionCode()).orElse("");
                return planId + "_" + name + "_" + code;
            }, Function.identity(), (v1, v2) -> v1));
        } else {
            positionMap = new HashMap<>();
        }

        ExcelUtil.readBySax(filePath, 0, (int sheetIndex, long rowIndex, List<Object> rowList) -> {
            if (rowIndex > 1) {
                num.getAndSet(num.get() + 1);
                if (rowList.size() < 12) {
                    int size = rowList.size();
                    for (int i = 0; i < 12 - size; i++) {
                        rowList.add("");
                    }
                }
                // 验证必填字段
                if (StrUtil.isEmptyIfStr(rowList.get(0).toString().trim())) {
                    rowList.add(0, "计划名称不能为空");
                    errList.add(rowList);
                    return;
                }
                if (StrUtil.isEmptyIfStr(rowList.get(1).toString().trim())) {
                    rowList.add(0, "计划编号不能为空");
                    errList.add(rowList);
                    return;
                }

                String planKey = rowList.get(0).toString().trim() + rowList.get(1).toString().trim();
                if (!planMap.containsKey(planKey)) {
                    rowList.add(0, "计划不存在");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPlan plan = planMap.get(planKey);
                if (plan == null) {
                    rowList.add(0, "计划不存在");
                    errList.add(rowList);
                    return;
                }

                // 验证记录编号
                if (StrUtil.isEmptyIfStr(rowList.get(2).toString().trim())) {
                    rowList.add(0, "记录编号不能为空");
                    errList.add(rowList);
                    return;
                }

                String recordCode = rowList.get(2).toString().trim();
                if (!recordMap.containsKey(recordCode)) {
                    rowList.add(0, "记录不存在");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPlanRecord record = recordMap.get(recordCode);
                if (record == null) {
                    rowList.add(0, "记录不存在");
                    errList.add(rowList);
                    return;
                }

                // 验证记录是否属于该计划
                if (!Objects.equals(record.getPlanId(), plan.getPlanId())) {
                    rowList.add(0, "记录不属于该计划");
                    errList.add(rowList);
                    return;
                }

                // 验证岗位名称
                if (StrUtil.isEmptyIfStr(rowList.get(3).toString().trim())) {
                    rowList.add(0, "岗位名称不能为空");
                    errList.add(rowList);
                    return;
                }

                String positionName = rowList.get(3).toString().trim();
                if (StrUtil.isEmptyIfStr(rowList.get(4).toString().trim())) {
                    rowList.add(0, "岗位编号不能为空");
                    errList.add(rowList);
                    return;
                }
                String positionCode = rowList.get(4).toString().trim();

                String positionKey = plan.getPlanId() + "_" + positionName + "_" + positionCode;
                if (!positionMap.containsKey(positionKey)) {
                    rowList.add(0, "岗位不存在");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPosition position = positionMap.get(positionKey);
                if (position == null) {
                    rowList.add(0, "岗位不存在");
                    errList.add(rowList);
                    return;
                }
                if (!Objects.equals(Optional.ofNullable(position.getPositionCode()).orElse(""), positionCode)) {
                    rowList.add(0, "岗位编号不匹配");
                    errList.add(rowList);
                    return;
                }
                if (!Objects.equals(Optional.ofNullable(position.getPositionName()).orElse(""), positionName)) {
                    rowList.add(0, "岗位名称与编号不匹配");
                    errList.add(rowList);
                    return;
                }

                // 验证报名数量
                Integer registrationNum;
                if (StrUtil.isEmptyIfStr(rowList.get(5).toString().trim())) {
                    rowList.add(0, "报名数量不能为空");
                    errList.add(rowList);
                    return;
                }
                try {
                    registrationNum = Integer.parseInt(rowList.get(5).toString().trim());
                    if (registrationNum < 0) {
                        rowList.add(0, "报名数量必须大于等于0");
                        errList.add(rowList);
                        return;
                    }
                } catch (NumberFormatException e) {
                    rowList.add(0, "报名数量格式错误，必须为整数");
                    errList.add(rowList);
                    return;
                }

                // 验证入闱笔试数量
                Integer writtenNum = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(6))) {
                    try {
                        writtenNum = Integer.parseInt(rowList.get(6).toString().trim());
                        if (writtenNum < 0) {
                            rowList.add(0, "入闱笔试数量必须大于等于0");
                            errList.add(rowList);
                            return;
                        }
                    } catch (NumberFormatException e) {
                        rowList.add(0, "入闱笔试数量格式错误，必须为整数");
                        errList.add(rowList);
                        return;
                    }
                }

                // 验证笔试是否达开考比例
                Integer isWrittenExam = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(7))) {
                    String isWrittenExamStr = rowList.get(7).toString().trim();
                    if ("是".equals(isWrittenExamStr)) {
                        isWrittenExam = 1;
                    } else if ("否".equals(isWrittenExamStr)) {
                        isWrittenExam = 0;
                    } else {
                        rowList.add(0, "笔试是否达开考比例只能填写[是、否]");
                        errList.add(rowList);
                        return;
                    }
                }

                // 验证入闱面试数量
                Integer interviewNum = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(8))) {
                    try {
                        interviewNum = Integer.parseInt(rowList.get(8).toString().trim());
                        if (interviewNum < 0) {
                            rowList.add(0, "入闱面试数量必须大于等于0");
                            errList.add(rowList);
                            return;
                        }
                    } catch (NumberFormatException e) {
                        rowList.add(0, "入闱面试数量格式错误，必须为整数");
                        errList.add(rowList);
                        return;
                    }
                }

                // 验证面试是否达开考比例
                Integer isInterviewExam = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(9))) {
                    String isInterviewExamStr = rowList.get(9).toString().trim();
                    if ("是".equals(isInterviewExamStr)) {
                        isInterviewExam = 1;
                    } else if ("否".equals(isInterviewExamStr)) {
                        isInterviewExam = 0;
                    } else {
                        rowList.add(0, "面试是否达开考比例只能填写[是、否]");
                        errList.add(rowList);
                        return;
                    }
                }

                // 验证入闱体检人数
                Integer checkNum = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(10))) {
                    try {
                        checkNum = Integer.parseInt(rowList.get(10).toString().trim());
                        if (checkNum < 0) {
                            rowList.add(0, "入闱体检人数必须大于等于0");
                            errList.add(rowList);
                            return;
                        }
                    } catch (NumberFormatException e) {
                        rowList.add(0, "入闱体检人数格式错误，必须为整数");
                        errList.add(rowList);
                        return;
                    }
                }

                // 验证拟聘用人数
                Integer estimateNum = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(11))) {
                    try {
                        estimateNum = Integer.parseInt(rowList.get(11).toString().trim());
                        if (estimateNum < 0) {
                            rowList.add(0, "拟聘用人数必须大于等于0");
                            errList.add(rowList);
                            return;
                        }
                    } catch (NumberFormatException e) {
                        rowList.add(0, "拟聘用人数格式错误，必须为整数");
                        errList.add(rowList);
                        return;
                    }
                }

                HrmRecruitProces proces = new HrmRecruitProces();
                proces.setPlanId(plan.getPlanId());
                proces.setRecordId(record.getRecordId());
                proces.setPositionId(position.getPositionId());
                proces.setRegistrationNum(registrationNum);
                proces.setWrittenNum(writtenNum);
                proces.setIsWrittenExam(isWrittenExam);
                proces.setInterviewNum(interviewNum);
                proces.setIsInterviewExam(isInterviewExam);
                proces.setCheckNum(checkNum);
                proces.setEstimateNum(estimateNum);
                proces.setCreateTime(LocalDateTime.now());
                addProcesList.add(proces);
            } else {
                if (rowIndex == 1) {
                    rowList.add(0, "错误信息");
                }
                errList.add(Convert.toInt(rowIndex), rowList);
            }
        });

        if (!addProcesList.isEmpty()) {
            this.saveBatch(addProcesList);
        }
        FileUtil.del(filePath);
        JSONObject result = new JSONObject().fluentPut("totalSize", num.get()).fluentPut("errSize", 0);
        int listSize = 2;
        if (errList.size() > listSize) {
            File errFile = FileUtil.file("excelData/" + IdUtil.simpleUUID() + ".xlsx");
            BigExcelWriter writer = ExcelUtil.getBigWriter(errFile);
            // 取消数据的黑色边框以及数据左对齐
            CellStyle cellStyle = writer.getCellStyle();
            cellStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyle.setBorderTop(BorderStyle.NONE);
            cellStyle.setBorderBottom(BorderStyle.NONE);
            cellStyle.setBorderLeft(BorderStyle.NONE);
            cellStyle.setBorderRight(BorderStyle.NONE);
            cellStyle.setAlignment(HorizontalAlignment.LEFT);
            Font defaultFont = writer.createFont();
            defaultFont.setFontHeightInPoints((short) 11);
            cellStyle.setFont(defaultFont);
            // 取消数字格式的数据的黑色边框以及数据左对齐
            CellStyle cellStyleForNumber = writer.getStyleSet().getCellStyleForNumber();
            cellStyleForNumber.setBorderTop(BorderStyle.NONE);
            cellStyleForNumber.setBorderBottom(BorderStyle.NONE);
            cellStyleForNumber.setBorderLeft(BorderStyle.NONE);
            cellStyleForNumber.setBorderRight(BorderStyle.NONE);
            cellStyleForNumber.setAlignment(HorizontalAlignment.LEFT);
            cellStyleForNumber.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyleForNumber.setFont(defaultFont);

            CellStyle textStyle = writer.getWorkbook().createCellStyle();
            DataFormat format = writer.getWorkbook().createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));

            writer.merge(errList.get(1).size() + 1, errList.get(0).get(0).toString().trim(), true);
            writer.getHeadCellStyle().setAlignment(HorizontalAlignment.LEFT);
            writer.getHeadCellStyle().setWrapText(true);
            Font headFont = writer.createFont();
            headFont.setFontHeightInPoints((short) 11);
            writer.getHeadCellStyle().setFont(headFont);
            writer.getHeadCellStyle().setFillPattern(FillPatternType.NO_FILL);
            writer.getOrCreateRow(0).setHeightInPoints(120);
            writer.setRowHeight(-1, 20);

            for (int i = 0; i < errList.get(1).size(); i++) {
                writer.getSheet().setDefaultColumnStyle(i, textStyle);
            }
            errList.remove(0);
            writer.write(errList);
            writer.close();
            //将错误信息的excel保存七天 604800 七天的秒数
            MultipartFile multipartFile = MultipartFileUtil.getMultipartFile(errFile);
            UploadEntity uploadEntity = adminFileService.uploadTempFile(multipartFile, IdUtil.simpleUUID()).getData();

            redis.setex(AdminCacheKey.UPLOAD_EXCEL_MESSAGE_PREFIX + "file:" + uploadEntity.getFileId(), 604800, uploadEntity.getPath());

            result.fluentPut("errSize", errList.size() - 1).fluentPut("token", uploadEntity.getFileId());
        }
        return result;
    }

    @Override
    public UploadEntity uploadTempFile(MultipartFile file, String batchId) {
        Result<UploadEntity> result = adminFileService.uploadTempFile(file, batchId);
        return result.getData();
    }

}

